package com.dlc.shop.seckill.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.ProcessActivityProdPriceEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.param.ProductParam;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 处理活动商品价格的事件
 * @author lhd
 */
@Component("processSeckillProdPriceListener")
@AllArgsConstructor
public class ProcessActivityProdPriceListener {

    private final SeckillService seckillService;

    @EventListener(ProcessActivityProdPriceEvent.class)
    public void processSeckillProdPrice(ProcessActivityProdPriceEvent event) {
        ProductParam productParam = event.getProduct();
        if(Objects.isNull(productParam.getProdType()) || !Objects.equals(productParam.getProdType(), ProdType.PROD_TYPE_SECKILL.value())) {
            return;
        }
        List<Product> products = event.getProducts();
        List<Long> prodIds = new ArrayList<>();
        products.forEach(product -> prodIds.add(product.getProdId()));
        Date date = new Date();
        List<Seckill> seckillList = seckillService.list(new LambdaQueryWrapper<Seckill>()
                .eq(Seckill::getStatus, 1).lt(Seckill::getStartTime, date)
                .gt(Seckill::getEndTime, date).in(Seckill::getProdId, prodIds));
        Map<Long, Double> priceMap = seckillList.stream().collect(Collectors.toMap(Seckill::getProdId, Seckill::getSeckillPrice));
        for (Product product : products) {
            Double price = priceMap.get(product.getProdId());
            product.setActivityPrice(price);
        }
    }

}
